package com.yumei.trader.gym.client;

import static com.yumei.trader.gym.ktx.ActivityKtxKt.getGuideUrl;
import static com.yumei.trader.gym.ktx.DialogKtxKt.createDialog;

import static java.lang.Thread.sleep;

import android.annotation.SuppressLint;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingResult;
import com.yumei.trader.gym.R;
import com.yumei.trader.gym.dbase.DBaseConst;
import com.yumei.trader.gym.google.GoogleConst;
import com.yumei.trader.gym.google.GoogleHelper;
import com.yumei.trader.gym.ktx.MCallBack;
import com.yumei.trader.gym.page.PageAppGuide;
import com.yumei.trader.gym.page.PageAppHome;
import com.yumei.trader.gym.util.DateUtil;
import com.yumei.trader.gym.util.StringUtils;

import java.util.Calendar;


public class AppStartPage extends BasePage implements MCallBack {

    private ImageView imgStart;
    private AnimationDrawable AD;

    private String nowDateStr;
    private String haveReward = "";

    private TGApplication mApp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApp = (TGApplication) this.getApplication();
        setContentView(R.layout.page_app_start);
        registerComponent();
       // requestData();
        mHandler.postDelayed(() -> {
            mHandler.sendEmptyMessage(0);
        }, 1000);
    }

    @Override
    protected void onResume() {
        super.onResume();
        transparentBar();
    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                judgeIsFirstStart();
            }
        }
    };

    private void checkAction() {

        nowDateStr = DateUtil.toDateStr(Calendar.getInstance());
        String lastCheckDate = mApp.getDBMrg().getValue(DBaseConst.Time_Last_Check, "2020-07-21");
        if (lastCheckDate.compareTo(nowDateStr) < 0) {
            System.out.println("++++++++++++++");
            haveReward = "yes";
        }
    }

    private void registerComponent() {

        imgStart = this.findViewById(R.id.img_start);
        imgStart.setImageResource(R.drawable.anim_start);

        AD = (AnimationDrawable) imgStart.getDrawable();
        AD.setOneShot(false);

        checkAction();
        checkService();
    }

    @Override
    protected void onStart() {
        super.onStart();

        startAnimation();
    }

    private void checkService() {

        GoogleHelper googleObject = GoogleHelper.initInstance(this, GoogleConst.base64EncodedPublicKey);

        googleObject.connectGooglePlay(new BillingClientStateListener() {

            @Override
            public void onBillingSetupFinished(@NonNull BillingResult billingResult) {

                int code = billingResult.getResponseCode();
                mApp.isConnectGoogle = BillingClient.BillingResponseCode.OK == code;
            }

            @Override
            public void onBillingServiceDisconnected() {

            }
        });
    }

    private void judgeIsFirstStart() {

        boolean isFirst = Boolean.parseBoolean(mApp.getDBMrg().getValue(DBaseConst.Is_First_Start, "true"));
        if (isFirst) {
            showGuideScreen();
        } else {
            showHomeScreen();
        }
    }

    /**
     * 主界面
     */
    private void showHomeScreen() {
        if (StringUtils.isNull(haveReward)) {
            startActivity(PageAppHome.class);
        } else {
            startActivity(PageAppHome.class, "haveReward", haveReward);
        }
        mApp.getDBMrg().addParam(DBaseConst.Time_Last_Check, nowDateStr);
        mApp.getDBMrg().save();
        this.finish();
    }

    private void requestData() {
        getGuideUrl(this, this);
    }

    /**
     * 启动引导页
     */
    private void showGuideScreen() {
        startActivity(PageAppGuide.class);
        this.finish();
    }

    private void startAnimation() {
        AD.start();
        Animation trans = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
        trans.setDuration(3700);
        trans.setRepeatCount(Animation.INFINITE);
        imgStart.startAnimation(trans);
    }


    @Override
    public void onSuc(@NonNull String url) {
        createDialog(this, url, () -> {
            mHandler.postDelayed(() -> {
                mHandler.sendEmptyMessage(0);
            }, 1000);
            return null;
        });
    }

    @Override
    public void onFailed() {
        new Thread(() -> {
            try {
                sleep(5000L);
                requestData();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }).start();
    }
}